package getip

import (
	"io/ioutil"
	"net/http"
	"time"
)

// getIp 获取当前的 ip 地址。
func GetIp() (res string, err error) {
	url := "http://ip-api.com/json/?fields=status,message,query"
	// return {"status":"success","query":"124.79.16.186"}
	var client http.Client
	var resp *http.Response

	// 设置超时时间
	client = http.Client{Timeout: 10 * time.Second}

	// 使用get方法获取url
	resp, err = client.Get(url)
	if err != nil {
		return "", err
	}
	// 释放对象
	defer resp.Body.Close()

	// 把获取到的对象返回
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	defer client.CloseIdleConnections()

	// byte 转string
	res = string(body)

	return res, nil
}
